package com.et.u1.uitl

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
import android.os.Handler
import android.os.Message
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import android.text.format.DateFormat
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.et.u1.R
import com.et.u1.databinding.ActivityMainBinding
import java.net.HttpURLConnection
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*


@Suppress("DEPRECATION")
class ActionBarManager(
    private var binding: ActivityMainBinding,
    private var context: Context
) {
    private lateinit var mTelephonyManager: TelephonyManager
    private var netUtil: NetUtil = NetUtil(context)
    private var signalLevel: Int = -1
    private var wifiLevel: Int = -2
    private var signalType: String = ""
    private var signal: String = ""
    private var delayTime: Long = 60 * 1000

    init {
        netUtil = NetUtil(context)
    }

    @SuppressLint("SetTextI18n")
    fun initActionBar() {

        binding.version.text = "机器编号：$uuid"
        binding.signalType.text = "正在检测..."

        object : Thread() {
            override fun run() {
                do {
                    handler.sendEmptyMessage(2)
                    sleep(1000)
                } while (true)
            }
        }.start()

        object : Thread() {
            override fun run() {
                getHttp()
                do {
                    getHttp()
                    sleep(delayTime)
                } while (true)
            }
        }.start()
    }

    val handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    //设置时间
                    val time = System.currentTimeMillis()
                    val format: CharSequence = DateFormat.format("yyyy-MM-dd HH:mm:ss", time)
                    binding.time.text = format

                    //刷新手机信号
                    if (netUtil.hasSimCard()) {
                        binding.signalImage.visibility = View.VISIBLE
                        getMobileNetworkSignal()
                    } else {
                        binding.signalImage.visibility = View.GONE
                    }

                    if (signalType != netUtil.phone) {
                        binding.signalType.text = netUtil.phone
                        signalType = netUtil.phone
                        Log.d("已修改信号类型", "" + netUtil.phone)
                    }
                    Log.d("信号类型", "" + netUtil.phone)


                    if (netUtil.networkType == "WIFI") {
                        binding.wifiImage.visibility = View.VISIBLE
                        binding.netType.visibility = View.GONE
                        if (netUtil.wifi != wifiLevel) {
                            when (netUtil.wifi) {
                                1 -> {
                                    binding.wifiImage.setImageResource(R.mipmap.w_1)
                                    delayTime = 1 * 1000
                                }
                                2 -> {
                                    binding.wifiImage.setImageResource(R.mipmap.w_2)
                                    delayTime = 5 * 1000
                                }
                                3 -> {
                                    binding.wifiImage.setImageResource(R.mipmap.w_3)
                                    delayTime = 40 * 1000
                                }
                                4 -> {
                                    binding.wifiImage.setImageResource(R.mipmap.w_4)
                                    delayTime = 60 * 1000
                                }
                            }
                            Log.d("已修改WiFi信号", "" + netUtil.wifi)
                            wifiLevel = netUtil.wifi
                        }
                        Log.d("WiFi信号", "" + netUtil.wifi)
                    } else {
                        binding.wifiImage.visibility = View.GONE
                        binding.netType.visibility = View.VISIBLE
                        if (signal != netUtil.networkType) {
                            binding.netType.text = netUtil.networkType
                            signal = netUtil.networkType
                        }
                    }
                }
                2 -> {
                    //设置时间
                    binding.time.text = SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss",
                        Locale.getDefault()
                    ).format(System.currentTimeMillis())
                }
                3 -> {
                    if (signalType != netUtil.phone) {
                        binding.signalType.text = netUtil.phone
                        signalType = netUtil.phone
                        Log.d("已修改信号类型", "" + netUtil.phone)
                    }
                    Log.d("信号类型", "" + netUtil.phone)

                    val level = msg.obj
                    if (netUtil.networkType == "WIFI") {
                        binding.wifiImage.visibility = View.VISIBLE
                        binding.netType.visibility = View.GONE
                        if (level != wifiLevel) {
                            when (level) {
                                0 -> {
                                    Log.d("level", "0")
                                    binding.wifiImage.setImageResource(R.mipmap.w_1)
                                    binding.signalImage.setImageResource(R.mipmap.s_1)
                                    delayTime = 1 * 1000
                                }
                                1 -> {
                                    Log.d("level", "1")
                                    binding.wifiImage.setImageResource(R.mipmap.w_1)
                                    binding.signalImage.setImageResource(R.mipmap.s_0)
                                    delayTime = 5 * 1000
                                }
                                2 -> {
                                    Log.d("level", "2")
                                    binding.wifiImage.setImageResource(R.mipmap.w_2)
                                    binding.signalImage.setImageResource(R.mipmap.s_2)
                                    delayTime = 10 * 1000
                                }
                                3 -> {
                                    binding.wifiImage.setImageResource(R.mipmap.w_3)
                                    binding.signalImage.setImageResource(R.mipmap.s_3)
                                    delayTime = 40 * 1000
                                }
                                4 -> {
                                    binding.wifiImage.setImageResource(R.mipmap.w_4)
                                    binding.signalImage.setImageResource(R.mipmap.s_4)
                                    delayTime = 60 * 1000
                                }
                            }
                            wifiLevel = level as Int
                        }
                    } else {
                        binding.wifiImage.visibility = View.GONE
                        binding.netType.visibility = View.VISIBLE
                        if (signal != netUtil.networkType) {
                            binding.netType.text = netUtil.networkType
                            signal = netUtil.networkType
                        }
                        if (level != wifiLevel) {
                            when (level) {
                                0 -> {
                                    binding.signalImage.setImageResource(R.mipmap.s_1)
                                    delayTime = 1 * 1000
                                }
                                1 -> {
                                    binding.signalImage.setImageResource(R.mipmap.s_0)
                                    delayTime = 5 * 1000
                                }
                                2 -> {
                                    binding.signalImage.setImageResource(R.mipmap.s_2)
                                    delayTime = 10 * 1000
                                }
                                3 -> {
                                    binding.signalImage.setImageResource(R.mipmap.s_3)
                                    delayTime = 40 * 1000
                                }
                                4 -> {
                                    binding.signalImage.setImageResource(R.mipmap.s_4)
                                    delayTime = 60 * 1000
                                }
                                -1 -> {
                                    // TODO: 2021/7/21 无网络
                                    binding.signalImage.setImageResource(R.mipmap.s_1)
                                }
                            }
                            wifiLevel = level as Int
                        }
                    }

                }
            }
        }
    }

    private fun getMobileNetworkSignal() {
        mTelephonyManager =
            context.getSystemService(AppCompatActivity.TELEPHONY_SERVICE) as TelephonyManager
        mTelephonyManager.listen(object : PhoneStateListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            override fun onSignalStrengthsChanged(signalStrength: SignalStrength) {
                super.onSignalStrengthsChanged(signalStrength)
                if (signalStrength.level != signalLevel) {
                    when (signalStrength.level) {
                        0 -> {
                            binding.signalImage.setImageResource(R.mipmap.s_1)
                            delayTime = 1 * 1000
                        }
                        1 -> {
                            binding.signalImage.setImageResource(R.mipmap.s_0)
                            delayTime = 5 * 1000
                        }
                        2 -> {
                            binding.signalImage.setImageResource(R.mipmap.s_2)
                            delayTime = 40 * 1000
                        }
                        3 -> {
                            binding.signalImage.setImageResource(R.mipmap.s_3)
                            delayTime = 40 * 1000
                        }
                        4 -> {
                            binding.signalImage.setImageResource(R.mipmap.s_4)
                            delayTime = 60 * 1000
                        }
                    }
                    signalLevel = signalStrength.level
                    Log.d("已修改手机信号", "" + signalStrength.level)

                }
                Log.d("手机信号", "" + signalStrength.level)
            }
        }, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)

    }

    private fun getHttp() {
        if (checkConnectNetwork(context)) {
            var runTime: Long
            object : Thread() {
                override fun run() {
                    super.run()
                    var conn: HttpURLConnection? = null
                    try {
                        //起始时间
                        val startTime = System.currentTimeMillis()
                        val url = URL("http://www.baidu.com")
                        conn = url.openConnection() as HttpURLConnection
                        conn.requestMethod = "GET"
                        conn.connectTimeout = 5000
                        conn.connect()
                        //结束时间
                        val endTime = System.currentTimeMillis()
                        runTime = endTime - startTime
                        Log.d("time===", runTime.toString())
                        val message = Message()
                        message.what = 3
                        when (runTime) {
                            in 0..100 -> {
                                message.obj = 4
                            }
                            in 101..200 -> {
                                message.obj = 3
                            }
                            in 201..300 -> {
                                message.obj = 2
                            }
                            in 301..400 -> {
                                message.obj = 1
                            }
                            else -> {
                                message.obj = 0
                            }
                        }
                        handler.sendMessage(message)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        conn?.disconnect()
                    }

                }
            }.start()
        } else {
            val message = Message()
            message.what = 3
            message.obj = -1
            handler.sendMessage(message)
            Log.d("TAG", "无网络连接！")
        }

    }


    //判断是否联网
    private fun checkConnectNetwork(context: Context): Boolean {
        val conn = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val net = conn.activeNetworkInfo
        return net != null && net.isConnected
    }

}